<template>
	<view class="search">
		<view class="uni_search_box">
			<view class="uni_search">
				<uni-search-bar class="uni_search_bar" @input="input" :radius="5" cancelButton="none"
					placeholder="请输入搜索内容"></uni-search-bar>
			</view>
		</view>
		<view v-if="keyword.length==0">
			<view>
				<view class="dq_watch_history">
					<text>浏览历史</text>
					<uni-icons type="trash-filled" @click="clean"></uni-icons>
				</view>
			</view>
			<view class="dq_tags">
				<uni-tag class="dq_tags_item" v-for="item in historyList" :key="item" :text="item" @click="historyTagHandle(item)"/>
			</view>
		</view>
		<template v-else>
			<my-advise v-for="item in adviseList" :key="item.goods_id" :title="item.goods_name"
				@myClick="gotoGoodsDetail(item)"></my-advise>
		</template>
	</view>
</template>

<script setup>
	import {
		ref
	} from "vue"
	import myAdvise from "../../components/myAdvise/myAdvise.vue"
	import {onLoad } from "@dcloudio/uni-app"
	// 搜索信息
	const keyword = ref("");
	const timer = ref(null);
	//建议列表
	const adviseList = ref([])
	// 历史列表
	const historyList = ref([])
	//获取建议列表
	const getAdviseList = async (query) => {
		const res = await uni.$http.get("/api/public/v1/goods/qsearch", {
			query
		})
		if (res.data.meta.status !== 200) return uni.$showMsg()
		adviseList.value = res.data.message
	}
	// 触发input事件
	const input = (e) => {
		clearTimeout(timer.value)
		timer.value = setTimeout(() => {
			keyword.value = e;
			if (keyword.value.length == 0) {
				adviseList.value = []
				return;
			}
			getAdviseList(keyword.value)
		}, 500)
	}
	// 跳转商品详情
	const gotoGoodsDetail = (query) => {
		uni.navigateTo({
			url: "/subpkg/goods_detail/goods_detail?goods_id=" + query.goods_id
		})
		historyList.value.push(keyword.value)
		historyList.value = historyList.value.reverse()
		historyList.value = [...new Set(historyList.value)]
		uni.setStorageSync("keyword",JSON.stringify(historyList.value))
	}
	// 清空历史记录
	const clean=()=>{
		historyList.value=[]
		uni.setStorageSync("keyword",'[]')
	}
	//点击历史记录
	const historyTagHandle=(query)=>{
		uni.navigateTo({
			url:"/subpkg/goods_list/goods_list?query="+query
		})
	}
	// 页面刷新
onLoad(()=>{
	historyList.value=JSON.parse(uni.getStorageSync("keyword")||'[]')
})
</script>

<style lang="scss" scoped>
	.search {
		width: 100%;

		.dq_watch_history {
			height: 65rpx;
			display: flex;
			justify-content: space-between;
			align-items: center;
			font-size: 24rpx;
			padding: 0 10px;
		}

		.uni_search_box {
			background-color: #c00000;
			height: 100rpx;
			display: flex;
			justify-content: center;
			align-items: center;
			position: sticky;
			top: 0;
			z-index: 99999999;

			.uni_search {
				width: 88%;
				margin: 0 auto;
			}
		}

		.dq_tags {
			padding: 0 10px;

			.dq_tags_item {
				overflow: hidden;
				text-overflow: ellipsis;
				white-space: nowrap;
				padding-right: 8px;
			}
		}
	}
</style>
